<template>
    <a-card>
        <div :class="advanced ? 'search' : null">
            <a-form layout="horizontal">
                <div :class="advanced ? null: 'fold'">
                    <a-row>
                        <a-col :md="8" :sm="24">
                            <a-form-item
                                    label="角色名称"
                                    :labelCol="{span: 5}"
                                    :wrapperCol="{span: 18, offset: 1}"
                            >
                                <a-input placeholder="请输入"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row v-if="advanced">
                        <a-col :md="8" :sm="24">
                            <a-form-item
                                    label="创建日期"
                                    :labelCol="{span: 5}"
                                    :wrapperCol="{span: 18, offset: 1}"
                            >
                                <a-date-picker style="width: 100%" placeholder="请输入更新日期"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
                <span style="float: right; margin-top: 3px;">
          <a-button type="primary">查询</a-button>
          <a-button style="margin-left: 8px">重置</a-button>
          <a @click="toggleAdvanced" style="margin-left: 8px">
            {{advanced ? '收起' : '展开'}}
            <a-icon :type="advanced ? 'up' : 'down'"/>
          </a>
        </span>
            </a-form>
        </div>
        <div>
            <a-space class="operator">
                <a-button @click="addRole" type="primary">新建</a-button>
                <a-button>批量操作</a-button>
                <a-dropdown>
                    <a-menu @click="handleMenuClick" slot="overlay">
                        <a-menu-item key="delete">删除</a-menu-item>
                    </a-menu>
                    <a-button>
                        更多操作
                        <a-icon type="down"/>
                    </a-button>
                </a-dropdown>
            </a-space>
            <standard-table
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :selectedRows.sync="selectedRows"
                    @clear="onClear"
                    @change="onChange(arguments)"
                    @selectedRowChange="onSelectChange"
            >
                <div slot="description" slot-scope="{text}">
                    {{text}}
                </div>
                <div slot="action" slot-scope="{text, record}">
                    <a style="margin-right: 8px" @click="editRole(record)">
                        <a-icon type="edit"/>
                        编辑
                    </a>
                    <a-popconfirm
                            title="确定删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="confirmDelete(record.id)"

                    >
                        <a>
                            <a-icon type="delete"/>
                            删除
                        </a>
                    </a-popconfirm>
                </div>
                <template slot="statusTitle">
                    <a-icon @click.native="onStatusTitleClick" type="info-circle"/>
                </template>
            </standard-table>
        </div>
        <a-modal
                :title="action==='edit' ? '编辑角色' : '新增角色'"
                :visible="visible"
                :footer="null"
                destroyOnClose
                :confirm-loading="confirmLoading"
                @cancel="handleCancel"
        >
            <a-form @submit="submit" :form="form">
                <a-form-item
                        :label="$t('id')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                        v-if="action==='edit'"
                >
                    <a-input disabled   v-decorator="['id',{}]"/>
                </a-form-item>
                <a-form-item
                        :label="$t('roleName')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"

                >
                    <a-input :placeholder="$t('roleNameInput')" allow-clear  v-decorator="['roleName', {rules: [{ required: true, message: $t('roleNameInput'), whitespace: true}]}]"/>
                </a-form-item>
                <a-form-item
                        :label="$t('remark')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-input :placeholder="$t('remarkInput')"  v-decorator="['remark',{}]" allow-clear/>
                </a-form-item>
                <a-form-item
                        :label="$t('grant')"
                        :labelCol="{span: 7}"
                        :wrapperCol="{span: 10}"
                >
                    <a-tree
                            v-model="checkedKeys"
                            checkable
                            style="width: 100%"
                            :tree-data="treeData"
                            :placeholder="$t('grant')"
                            v-decorator="['grant', {}]"
                            @check="onCheck"
                    >
                        <span slot="title" slot-scope="{ menuId, value }" style="color: #08c">
                        </span>
                    </a-tree>
                </a-form-item>
                <a-form-item style="margin-left: 30px;margin-top: 24px" :wrapperCol="{span: 10, offset: 7}">
                    <a-button type="primary" htmlType="submit">{{$t('submit')}}</a-button>
                    <a-button style="margin-left: 8px" @click="handleCancel">{{$t('cancel')}}</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </a-card>
</template>

<script>
    import StandardTable from '@/components/table/StandardTable'
    import {getRoleList, getRoleInfo, updateRole, saveRole, deleteRole} from '@/services/role'
    import {menuSelect} from '@/services/menu'

    const columns = [
        {
            title: 'id',
            dataIndex: 'id'
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
        },
        {
            title: '描述',
            dataIndex: 'remark',
            sorter: true,
        },
        {
            dataIndex: '创建人',
            slots: {title: 'createBy'}
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: true
        },
        {
            title: '操作',
            scopedSlots: {customRender: 'action'}
        }
    ];

    export default {
        name: 'roleList',
        i18n: require('./i18n'),
        components: {StandardTable},
        data() {
            return {
                form: this.$form.createForm(this),
                visible: false,
                confirmLoading: false,
                advanced: false,
                columns: columns,
                dataSource: [],
                selectedRows: [],
                checkedKeys: [],
                menuSelected: [],
                treeData: [],
                action: '',
                page: 1,
                limit: 10,
                total: 0
            }
        },
        authorize: {
            deleteRecord: 'delete'
        },
        created() {
            //获取角色列表
            this.getRoleList();
        },
        methods: {
            onCheck(e) {
                this.menuSelected = e;
            },
            menuSelect() {
                menuSelect().then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.treeData = res.result
                    } else {
                        this.$message.error(res.message, 3)
                    }
                })
            },
            /** 确认删除**/
            confirmDelete(id){
                const ids = [];
                ids.push(id);
                this.deleteRole(ids)
            },
            /** 删除角色**/
            deleteRole(ids){
                deleteRole(ids).then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.$message.success("操作成功", 1);
                        this.getRoleList();
                    } else {
                        this.$message.error(res.message, 1)
                    }
                });
            },
            /** 添加角色**/
            addRole() {
                //清空表单
                this.form.resetFields();
                //清空选中
                this.checkedKeys = [];
                //树形菜单渲染
                this.menuSelect();
                //新增行为
                this.action = 'add';
                this.visible = true;
            },
            /** 修改角色**/
            editRole(record) {
                console.log(record)
                //清空表单
                this.form.resetFields();
                //编辑行为
                if (record) {
                    this.action = 'edit';
                }
                //清空选中
                this.checkedKeys = [];
                //树形菜单渲染
                this.menuSelect();
                this.visible = true;
                //数据回显
                this.$nextTick(() => {
                    this.form.setFieldsValue({ // form表单赋值
                        id: record.id,
                        roleName: record.roleName,
                        remark: record.remark,
                    });
                });
                setTimeout(() => { // 添加延时操作,解决'1' does not exist in the tree
                    //树形菜单回显
                    this.checkedKeys = record.menuIdList;
                },600);
            },
            submit(e) {
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        const id = this.form.getFieldValue('id');
                        const roleName = this.form.getFieldValue('roleName');
                        const remark = this.form.getFieldValue('remark');
                        const menuIdList = this.menuSelected ? this.checkedKeys : this.menuSelected;
                        if (this.action === 'add') {
                            saveRole(roleName, remark,menuIdList).then(result => {
                                const res = result.data;
                                if (res && res.code === "00000") {
                                    this.$message.success(res.message, 1)
                                } else {
                                    this.$message.error(res.message, 1)
                                }
                            })
                        } else {
                            updateRole(id, roleName, remark,menuIdList ).then(result => {
                                const res = result.data;
                                if (res && res.code === "00000") {
                                    this.$message.success(res.message, 1)
                                } else {
                                    this.$message.error(res.message, 1)
                                }
                            })
                        }
                        //刷新列表
                        this.getRoleList();
                    }
                });
                this.visible = false;
            },
            handleCancel() {
                this.visible = false;
            },
            getRoleList() {
                getRoleList(this.page, this.limit, undefined).then(result => {
                    const res = result.data;
                    if (res && res.code === "00000") {
                        this.dataSource = res.result.list
                    } else {
                        this.$message.error(res.message, 3)
                    }
                })
            },
            toggleAdvanced() {
                this.advanced = !this.advanced
            },
            onClear() {
                this.$message.info('您清空了勾选的所有行')
            },
            onStatusTitleClick() {
                this.$message.info('你点击了状态栏表头')
            },
            onChange(e) {
                console.log(e);
                this.$message.info('表格状态改变了')
            },
            onSelectChange() {
                this.$message.info('选中行改变了')
            },
            handleMenuClick(e) {
                if (e.key === 'delete') {
                    //删除
                    let self = this;
                    this.$confirm({
                        title: '确认提示',
                        content: `是否确认删除？`,
                        okButtonProps: {
                            color: this.themeColor,
                        },
                        onOk () {
                            self.selectedRows = self.selectedRows.map((item) => item.id);
                            self.deleteRole(self.selectedRows);
                        }
                    });
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .search {
        margin-bottom: 54px;
    }

    .fold {
        width: calc(100% - 216px);
        display: inline-block
    }

    .operator {
        margin-bottom: 18px;
    }

    @media screen and (max-width: 900px) {
        .fold {
            width: 100%;
        }
    }
</style>
